#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include "methodpost.h"
#include "templates.h"

int DataVerificate(const char * const data)
{
	char buffer[255];
	if (!(GetValue("first_name", data, buffer)) || !(GetValue("last_name", data, buffer)) || !(GetValue("email", data, buffer)) ||
		!(GetValue("re_email", data, buffer)) || !(GetValue("password", data, buffer)) || !(GetValue("sex", data, buffer)) ||
		!(GetValue("month", data, buffer)) || !(GetValue("day", data, buffer)) || !(GetValue("year", data, buffer)))
	{
		return 0;
	}
	return 1;
}

int CompareEmails(const char * const data, char * email, char * reEmail)
{
	GetValue("email", data, email);
	GetValue("re_email", data, reEmail);
	return strcmp(ToLower(email), ToLower(reEmail));
}

void SaveToFile(const char * const data, char * fileName, char * reEmail)
{
	char * extension = ".txt";
	strncat(fileName, extension, strlen(extension));
	FILE * formData = fopen(ToLower(fileName), "wt");
	fprintf(formData, "%s\n", GetValue("first_name", data, fileName));
	fprintf(formData, "%s\n", GetValue("last_name", data, fileName));
	fprintf(formData, "%s\n", ToLower(reEmail));
	fprintf(formData, "%s\n", GetValue("password", data, fileName));
	fprintf(formData, "%s\n", GetValue("sex", data, fileName));
	fprintf(formData, "%s\n", GetValue("month", data, fileName));
	fprintf(formData, "%s\n", GetValue("day", data, fileName));
	fprintf(formData, "%s", GetValue("year", data, fileName));
	fclose(formData);
	formData = NULL;
}

void PrintResult(void)
{
	size_t n = atoi(getenv("CONTENT_LENGTH"));
	char * data = (char *)malloc(n + 2);
	memset(data, '\0', n + 2);
	fread(data + 1, 1, n + 1, stdin);
	data[0] = '?';
	char fileName[255], reEmail[255];
	if (!(DataVerificate(data)))
	{
		printf("<ul>\n<li><span>ERROR:</span> Not all fields are completed!</li>\n</ul>\n");
		return;
	}
	if (CompareEmails(data, fileName, reEmail))
	{
		printf("<ul>\n<li><span>ERROR:</span> E-Mail fields are not the same!</li>\n</ul>\n");
		return;
	}
	SaveToFile(data, fileName, reEmail);
	printf("<ul>\n<li>You have successfully signed up!</li>\n</ul>\n");
	free(data);
}

void main(void)
{
	PrintHTTPResponseHeader();
	PrintHTMLHead("Form", "Sign Up", "It's free and always will be.");
	PrintResult();
	PrintHTMLEnd();
}